package com.zp.base.admin.service.impl;

import com.zp.base.admin.common.utils.PageUtils;
import com.zp.base.admin.common.utils.Query;
import com.zp.base.admin.common.utils.StringAndDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zp.base.admin.dao.DatabaseBakDao;
import com.zp.base.admin.entity.DatabaseBakEntity;
import com.zp.base.admin.service.DatabaseBakService;
import org.springframework.transaction.annotation.Transactional;


@Service("databaseBakService")
@Transactional(rollbackFor = Exception.class)
public class DatabaseBakServiceImpl extends ServiceImpl<DatabaseBakDao, DatabaseBakEntity> implements DatabaseBakService {

    @Autowired
    DatabaseBakDao databaseBakDao;

    @Value("${zp.database.backup.dir}")
    private String backupDir;
    @Value("${zp.database.backup.username}")
    private String dbUsername;
    @Value("${zp.database.backup.password}")
    private String dbPassword;
    @Value("${zp.database.backup.db.name}")
    private String dbName;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<DatabaseBakEntity> page = this.page(
                new Query<DatabaseBakEntity>().getPage(params),
                new QueryWrapper<DatabaseBakEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public boolean deleteByIds(List<Long> ids) {
        try {
            //选查询所有要删除的备份记录
            List<DatabaseBakEntity> databaseBakEntities = databaseBakDao.selectList(new QueryWrapper<DatabaseBakEntity>().in("id", ids));
            //删除本地文件及备份信息
            for (DatabaseBakEntity databaseBakEntity : databaseBakEntities) {
                String path = databaseBakEntity.getFilepath() + databaseBakEntity.getFilename();
                File file = new File(path);
                if (!file.exists()) {
                    path = backupDir + databaseBakEntity.getFilename();
                    file = new File(path);
                }
                //先删除数据库信息再删除文件
                databaseBakDao.deleteById(databaseBakEntity.getId());
                file.delete();
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 数据库信息还原
     * @param id
     * @return
     */
    @Override
    public boolean restoreById(Long id) {
        try {
            DatabaseBakEntity databaseBakEntity = databaseBakDao.selectById(id);
            if (databaseBakEntity == null) {
                return false;
            }
            String path = databaseBakEntity.getFilepath() + databaseBakEntity.getFilename();
            String cmd = "mysql -u" + dbUsername + " -p" + dbPassword + " " + dbName + " < ";
            File file = new File(path);
            if (file.exists()) {
                cmd += path;
            } else {
                cmd += backupDir + databaseBakEntity.getFilename();
            }
            String stmt = "mysqladmin -u" + dbUsername + " -p" + dbPassword + " create " + dbName;
            String[] cmds = {"cmd", "/c", cmd};
            Runtime.getRuntime().exec(stmt);
            Process exec = Runtime.getRuntime().exec( cmds);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 数据库数据备份
     * @return
     */
    @Override
    public boolean saveDatabaseBakEntity() {
        try {
            File file = new File(backupDir);
            if (!file.exists()) {
                file.mkdir();
            }
            String filename = dbName + "_" + StringAndDateUtil.dateToString(new Date(), "yyyyMMddHHmmss") + ".sql";
            String path = backupDir + filename;
            String cmd = "mysqldump -u" + dbUsername + " -p" + dbPassword + " " + dbName + " -r " + path;
            Process exec = Runtime.getRuntime().exec(cmd);
            DatabaseBakEntity databaseBakEntity = new DatabaseBakEntity();
            databaseBakEntity.setCreateTime(new Date());
            databaseBakEntity.setUpdateTime(new Date());
            databaseBakEntity.setFilename(filename);
            databaseBakEntity.setFilepath(backupDir);
            databaseBakDao.insert(databaseBakEntity);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

}